package com.zhan.rkforum.config;

import com.zhan.rkforum.util.CommunityConstant;
import com.zhan.rkforum.util.CommunityUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter implements CommunityConstant {

    @Override
    public void configure(WebSecurity web) throws Exception {
//        super.configure(web);
        web.ignoring()
                .antMatchers("/resources/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        super.configure(http);
        /*
        /comment
        /discuss/add
        /follow
        /unfollow
        /like
        /logout
        /letter
        /user
         */
        http.formLogin()
                //.loginPage("/login")
                .loginProcessingUrl("/login")
                .successForwardUrl("/index")
                .failureForwardUrl("/error")
                .and().authorizeRequests()
                .antMatchers("/comment",
                        " /discuss/add",
                        "/follow",
                        "/unfollow",
                        "/like",
                        "/letter",
                        "/user")
                .hasAnyRole(AUTHORITY_USER,AUTHORITY_ADMIN, AUTHORITY_MODERATOR)
                .antMatchers("/discuss/top", "/discuss/refining")
                .hasRole(AUTHORITY_MODERATOR)
                .antMatchers("/discuss/delete","/data/**", "/data")
                .hasRole(AUTHORITY_ADMIN)
                .anyRequest().permitAll();

        http.exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPoint() {
            //没有登录时的处理
            @Override
            public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
                String xRequestedWith = httpServletRequest.getHeader("x-requested-with");
                if("XMLHttpRequest".equals(xRequestedWith)){
                    //异步请求
                    httpServletResponse.setContentType("application/plain;charset=utf-8");
                    PrintWriter writer = httpServletResponse.getWriter();
                    writer.write(CommunityUtil.getJsonString(403,"你还没有登录哦！"));
                }else {
                    //同步请求
                    httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/login");
                }
            }
        }).accessDeniedHandler(new AccessDeniedHandler() {
            //权限不足时的处理
            @Override
            public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
                String xRequestedWith = httpServletRequest.getHeader("x-requested-with");
                if("XMLHttpRequest".equals(xRequestedWith)){
                    //异步请求
                    httpServletResponse.setContentType("application/plain;charset=utf-8");
                    PrintWriter writer = httpServletResponse.getWriter();
                    writer.write(CommunityUtil.getJsonString(403,"你没有权限访问此页面哦！"));
                }else {
                    //同步请求
                    httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/denied");
                }
            }
        });
        //覆盖它默认的退出逻辑，使用我们的退出代码
        http.logout().logoutUrl("/" + CommunityUtil.generateUuid());
        //关闭csrf防护
        http.csrf().disable();
    }
}
